package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.*;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.ICourseSchedulingDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.IRecordCourseService;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 排课详情 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-01
 */
@Service
public class CourseSchedulingDetailServiceImpl extends ServiceImpl<CourseSchedulingDetailMapper, CourseSchedulingDetail> implements ICourseSchedulingDetailService {

    @Autowired
    @Lazy
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    @Lazy
    RecordCourseMapper recordCourseMapper;

    @Autowired
            @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    RepairCourseMapper repairCourseMapper;

    @Autowired
    LackCourseLogMapper lackCourseLogMapper;

    public CourseSchedulingDetail getOneById(Long id){
        return courseSchedulingDetailMapper.getOneById(id);
    }

    /**
     *
     * @param wrapper
     * @param schedulingId 排课详情id
     * @return
     */
    public List<RecordCourseStudent> recordStudentList(Wrapper wrapper,Long schedulingId,Long gradeId,Long courseId,Long schoolId){

        List<RecordCourseStudent> recordCourseStudentList = courseSchedulingDetailMapper.recordStudentList(wrapper);
        for (RecordCourseStudent recordCourseStudent:recordCourseStudentList){
            //System.out.print("schedulingId:"+schedulingId);
            //System.out.print("recordCourseStudent.getId():"+recordCourseStudent.getId());



            //获取已记上课数据，由于不需要修改，这里暂时注释
            recordCourseStudent.setRecordCourseTiny(new RecordCourseTiny());
            /*RecordCourseTiny recordCourseTiny = recordCourseMapper.getListForSchedulingIdAndStuId(schedulingId,recordCourseStudent.getId());
            if(recordCourseTiny == null){
                recordCourseStudent.setRecordCourseTiny(new RecordCourseTiny());
            }else {
                recordCourseStudent.setRecordCourseTiny(recordCourseTiny);
            }*/
            //recordCourseStudent.setRecordCourseTiny(new RecordCourseTiny());

            Course course = courseMapper.selectById(courseId);
            if(course == null){
                throw new CommonException(ResultCode.COURSE_NOT);
            }

            //剩余课时
            //OrderDetailTiny orderDetailTiny = orderDetailMapper.getResidueCourseCountForCourseId(recordCourseStudent.getId(),courseId,schoolId);
            OrderDetailTiny orderDetailTiny = orderDetailMapper.getResidueCourseCountForSubjectsId(recordCourseStudent.getId(),course.getSubjectsId(),schoolId,course.getLessonType());

            recordCourseStudent.setOrderDetailTiny(orderDetailTiny);
        }
        return recordCourseStudentList;
    }

    public List<CourseSchedulingDetail> findAll(Wrapper wrapper){
        List<CourseSchedulingDetail> courseSchedulingIPage = courseSchedulingDetailMapper.findAll(wrapper);
        return courseSchedulingIPage;
    }

    public IPage<CourseSchedulingDetail> findAllForPage(IPage<?> page,Wrapper wrapper){
        IPage<CourseSchedulingDetail> courseSchedulingIPage = courseSchedulingDetailMapper.findAllForPage(page,wrapper);
        return courseSchedulingIPage;
    }

    /**
     * 排课日程表
     * @param page
     * @param wrapper
     * @return
     */
    public IPage<CourseSchedulingDetail> calendarList(IPage<CourseSchedulingDetail> page,Wrapper wrapper){
        IPage<CourseSchedulingDetail> courseSchedulingDetailIPage = courseSchedulingDetailMapper.calendarList(page,wrapper);
        for (CourseSchedulingDetail courseSchedulingDetail:courseSchedulingDetailIPage.getRecords()){
            Long count = repairCourseMapper.selectCount(new QueryWrapper<RepairCourse>().eq("out_scheduling_detail_id",courseSchedulingDetail.getId()));
            courseSchedulingDetail.setOutStudentCount(count);
        }
        return courseSchedulingDetailIPage;
    }



    /**
     * 查找冲突排课
     * @param wrapper
     * @return
     */
    public List<CourseSchedulingDetail> getFindClash(Wrapper wrapper){
        Quarter quarter = iQuarterService.getNowQuarter();
        List<CourseSchedulingDetail> courseSchedulingDetailList = courseSchedulingDetailMapper.getFindClash(wrapper,quarter.getYearPart(),quarter.getNum());



        List<CourseSchedulingDetail> courseSchedulingDetailListResult = new ArrayList<>();
        for(CourseSchedulingDetail courseSchedulingDetail:courseSchedulingDetailList){

            QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
            courseSchedulingDetailQueryWrapper.eq("year_part",quarter.getYearPart());
            courseSchedulingDetailQueryWrapper.eq("quarter",quarter.getNum());
            courseSchedulingDetailQueryWrapper.eq("school_id",courseSchedulingDetail.getSchoolId());
            courseSchedulingDetailQueryWrapper.eq("grade_id",courseSchedulingDetail.getGradeId());
            courseSchedulingDetailQueryWrapper.eq("school_date",courseSchedulingDetail.getSchoolDate());
            courseSchedulingDetailQueryWrapper.eq("time_start",courseSchedulingDetail.getTimeStart());
            courseSchedulingDetailQueryWrapper.eq("time_end",courseSchedulingDetail.getTimeEnd());

            List<CourseSchedulingDetail> courseSchedulingDetailList2 = courseSchedulingDetailMapper.selectList(courseSchedulingDetailQueryWrapper);
            if(courseSchedulingDetailList2.size()>1){
                for(CourseSchedulingDetail courseSchedulingDetail2:courseSchedulingDetailList2){
                    Grade grade = gradeMapper.selectById(courseSchedulingDetail2.getGradeId());
                    if(grade != null){
                        courseSchedulingDetail.setGradeName(grade.getName());
                        Staff staff = staffMapper.selectById(grade.getTeacherId());
                        if(staff != null){
                            courseSchedulingDetail.setTeacherName(staff.getName());
                        }
                    }
                    courseSchedulingDetailListResult.add(courseSchedulingDetail2);
                }
            }
        }
        return courseSchedulingDetailListResult;
    }
    public IPage<CourseSchedulingDetail> getListByClassId(IPage<?> page, QueryWrapper queryWrapper){
        IPage<CourseSchedulingDetail> courseSchedulingDetailIPage = courseSchedulingDetailMapper.getListByClassId(page,queryWrapper);
        return courseSchedulingDetailIPage;
    }

    public List<Student> getStudentList(String id){
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        List<Student> studentList = new ArrayList<>();
        return studentList;
    }

    /**
     * 获取排课与调课、补课、消课信息
     * @param queryWrapper
     * @return
     */
    public List<RepairCourse> getSchedulingUnionRepair(QueryWrapper queryWrapper){
        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(queryWrapper);
        return repairCourseList;
    }

    public CourseSchedulingDetail getCourseSchedulingDetailById(Long id){
        return courseSchedulingDetailMapper.getCourseSchedulingDetailById(id);
    }


    public List<RepairCourse> getSchedulingList(Integer yearPart, Integer quarterNum, Long schoolId, Long studentId, LocalDate schoolDate){
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.eq("school_date",schoolDate);
        repairCourseQueryWrapper.eq("school_id",schoolId);
        repairCourseQueryWrapper.eq("deleted",0);
        repairCourseQueryWrapper.and(i->i.inSql("grade_id","select grade_id from student_grade where school_id = "+schoolId+" and status = 1 and reading_status=1 and year_part = "+yearPart+" and quarter_num="+quarterNum+" and student_id = "+studentId+" ").eq("scheduling_type",1).or(j->j.eq("student_id",studentId).eq("scheduling_type",2)));
        //repairCourseQueryWrapper.eq("grade_id",gr)
        repairCourseQueryWrapper.notInSql("id","select IFNULL(out_scheduling_detail_id,0) from repair_course where deleted=0 and course_type=4 and school_id = "+schoolId+" and year_part = "+yearPart+" and quarter="+quarterNum+" and student_id = "+studentId+"");//排除已经调课出去的
        repairCourseQueryWrapper.orderByAsc("start_date_time");
        List<RepairCourse>  repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);
        return repairCourseList;
    }


    /**
     * 删除当前时间之后的排课
     * @param gradeId
     * @return
     */
    public boolean deleteForGradeId(Long gradeId, LocalDateTime dateTime){
        Long rs = courseSchedulingDetailMapper.deleteForGradeId(gradeId,dateTime);
        if (rs != null && rs>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Integer getSchedulingCountForRecord(Long gradeId){
        return courseSchedulingDetailMapper.getSchedulingCountForRecord(gradeId);
    }

    public Long getIsAt(Long gradeId,Integer lessonNum){
        return  courseSchedulingDetailMapper.getIsAt(gradeId,lessonNum);
    }

    @Override
    public Long getIsAtForDate(Long gradeId,LocalDate schoolDate){
        return  courseSchedulingDetailMapper.getIsAtForDate(gradeId,schoolDate);
    }

    public List<RepairCourse> getSchoolDateList(String schoolId, String gradeId, String teacherId,String schoolDate,String lessonType){
        return courseSchedulingDetailMapper.getSchoolDateList(schoolId,gradeId,teacherId,schoolDate,lessonType);
    }


    public List<ArrivalRate> arrivalRate(String schoolIdStr, String yearPart, String quarterNum,String type,String subjectsId, String startDate, String endDate,String timeStart, String timeEnd, Integer lessonType, boolean isHistory){
        return  courseSchedulingDetailMapper.arrivalRate(schoolIdStr,yearPart,quarterNum,type,subjectsId,startDate,endDate,timeStart,timeEnd,lessonType,isHistory);
    }

    public List<RecordCourse> arrivalRateDetail(String schoolId,String subjectsId,String yearPart,String quarterNum,String startDate,String endDate,String gradeId,String teacherId,String type,String status,String timeStart,String timeEnd,Integer lessonType,boolean isHistory){
        return  courseSchedulingDetailMapper.arrivalRateDetail(schoolId,subjectsId,yearPart,quarterNum,startDate,endDate,gradeId,teacherId,type,status,timeStart,timeEnd,lessonType,isHistory);
    }

    @Override
    public List<SignResult> signInDetail(String schoolId, String subjectsId, String yearPart, String quarterNum, String startDate, String endDate, String gradeId, String teacherId, String type, String status, String timeStart, String timeEnd, Integer lessonType, String classTypeId, String studentName, boolean isHistory, List<RecordCourse> startAndEndList){
        String readingStatus = "1";

        Integer giveCount = courseSchedulingDetailMapper.getSignGiveCount(Integer.parseInt(yearPart),Integer.parseInt(quarterNum),LocalDate.now().toString());
        if (giveCount>0){
            readingStatus = "1,5";
        }
        return  courseSchedulingDetailMapper.signInDetail(schoolId,subjectsId,yearPart,quarterNum,startDate,endDate,gradeId,teacherId,type,status,timeStart,timeEnd,lessonType,classTypeId,studentName,isHistory,startAndEndList,readingStatus);
    }

    /**
     * 获取冲突课程
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param studentId
     * @param startDateTime
     * @param endDateTime
     * @return
     */
    @Override
    public List<SchedulingClash> schedulingClash(Integer yearPart, Integer quarterNum, Long schoolId, String studentId, String startDateTime, String endDateTime, String lessonType, String outSchedulingId){
        return  courseSchedulingDetailMapper.schedulingClash(yearPart,quarterNum,schoolId,studentId,startDateTime,endDateTime,lessonType,outSchedulingId);
    }

    public Long schedulingClashCount(Integer yearPart, Integer quarterNum, Long schoolId, Long studentId, String startDate, String endDate,String lessonType){
        return  courseSchedulingDetailMapper.schedulingClashCount(yearPart,quarterNum,schoolId,studentId,startDate,endDate,lessonType);
    }

    @Override
    //@Async("onlineAsync")
    public void updateLessonNum(Long gradeId){
        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        courseSchedulingDetailQueryWrapper.eq("grade_id",gradeId);
        courseSchedulingDetailQueryWrapper.orderByAsc("school_date");
        List<CourseSchedulingDetail> courseSchedulingDetailListNew = this.list(courseSchedulingDetailQueryWrapper);
        Integer i=1;
        for (CourseSchedulingDetail courseSchedulingDetail :courseSchedulingDetailListNew){
            courseSchedulingDetail.setLessonNum(i);
            this.updateById(courseSchedulingDetail);
            i++;
            //System.out.println("i："+i);
        }
        //return true;
    }

    @Override
    public Integer getNextLessonNum(Long gradeId,LocalDate schoolDate){
        return courseSchedulingDetailMapper.getNextLessonNum(gradeId,schoolDate);
    }

    @Override
    public LocalDate getGradeMinDate(Long gradeId){
        return courseSchedulingDetailMapper.getGradeMinDate(gradeId);
    }

    @Override
    public LocalDate getGradeMaxDate(Long gradeId){
        return courseSchedulingDetailMapper.getGradeMaxDate(gradeId);
    }


    /**
     * 获取学生的排课信息（包含补课，调课，消课）
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param schoolId
     * @param startSchoolDateTime
     * @return
     */
    @Override
    public List<RepairCourse> getCourseSchedulingList(Integer yearPart, Integer quarterNum, Long studentId, Long schoolId, String startSchoolDateTime){
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.gt(StringUtils.isNotBlank(startSchoolDateTime),"start_date_time",startSchoolDateTime);//上课时间大于
        //repairCourseQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
//        repairCourseQueryWrapper.eq("lesson_type",1);
        repairCourseQueryWrapper.eq("deleted",0);
        repairCourseQueryWrapper.and(i->i.inSql("grade_id","select grade_id from student_grade where  status = 1 and reading_status=1 and year_part = "+yearPart+" and quarter_num="+quarterNum+" and student_id = "+studentId+" ").eq("scheduling_type",1).or(j->j.eq("student_id",studentId).eq("scheduling_type",2)));
        repairCourseQueryWrapper.notInSql("id","select IFNULL(out_scheduling_detail_id,0) from repair_course where deleted=0 and course_type=4 and school_id = "+schoolId+" and year_part = "+yearPart+" and quarter="+quarterNum+" and student_id = "+studentId+"");//排除已经调课出去的
        //repairCourseQueryWrapper.notInSql("id","select IFNULL(out_scheduling_detail_id,0) from course_scheduling_clash where year_part = "+quarter.getYearPart()+" and quarter_num="+quarter.getNum()+" and student_id = "+studentId+"");//精品课与智能课或者刷题班课程冲突（排除智能课）
        repairCourseQueryWrapper.orderByAsc("start_date_time");
        List<RepairCourse>  repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);
        return repairCourseList;
    }

    @Override
    public List<RepairCourse> getCourseSchedulingListByLessonType(Integer yearPart, Integer quarterNum, Long studentId, Long schoolId, String startSchoolDateTime, Integer lessonType) {
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.gt(StringUtils.isNotBlank(startSchoolDateTime), "start_date_time", startSchoolDateTime);//上课时间大于
        //repairCourseQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
        repairCourseQueryWrapper.eq("lesson_type", lessonType);
        repairCourseQueryWrapper.eq("deleted", 0);
        repairCourseQueryWrapper.and(i -> i.inSql("grade_id", "select grade_id from student_grade where  status = 1 and reading_status=1 and year_part = " + yearPart + " and quarter_num=" + quarterNum + " and student_id = " + studentId + " ").eq("scheduling_type", 1).or(j -> j.eq("student_id", studentId).eq("scheduling_type", 2)));
        repairCourseQueryWrapper.notInSql("id", "select IFNULL(out_scheduling_detail_id,0) from repair_course where deleted=0 and course_type=4 and school_id = " + schoolId + " and year_part = " + yearPart + " and quarter=" + quarterNum + " and student_id = " + studentId + "");//排除已经调课出去的
        //repairCourseQueryWrapper.notInSql("id","select IFNULL(out_scheduling_detail_id,0) from course_scheduling_clash where year_part = "+quarter.getYearPart()+" and quarter_num="+quarter.getNum()+" and student_id = "+studentId+"");//精品课与智能课或者刷题班课程冲突（排除智能课）
        repairCourseQueryWrapper.orderByAsc("start_date_time");
        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);
        return repairCourseList;
    }

    /**
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param gradeId
     * @param localDateTime
     * @return
     */
    @Override
    public List<RepairCourse> getSchedulingClash(Integer yearPart, Integer quarterNum, Long studentId, Long gradeId, String localDateTime) {
        Grade grade = gradeMapper.selectById(gradeId);

        List<RepairCourse> repairCourseList = this.getCourseSchedulingList(yearPart, quarterNum, studentId, null, localDateTime);
        //获取出当前班级的排课
        List<CourseSchedulingDetail> courseSchedulingDetailList = courseSchedulingDetailMapper.getSchedulingForGradeId(yearPart, quarterNum, gradeId, grade.getLessonType(), localDateTime);

        //冲突排课
        List<RepairCourse> repairCourseClashList = new ArrayList<>();
        for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
            for (RepairCourse repairCourse : repairCourseList) {
                if ((courseSchedulingDetail.getStartDateTime().compareTo(repairCourse.getStartDateTime()) <= 0 && courseSchedulingDetail.getEndDateTime().compareTo(repairCourse.getStartDateTime()) >= 0) || (courseSchedulingDetail.getStartDateTime().compareTo(repairCourse.getEndDateTime()) <= 0 && courseSchedulingDetail.getEndDateTime().compareTo(repairCourse.getEndDateTime()) >= 0) || (courseSchedulingDetail.getStartDateTime().compareTo(repairCourse.getEndDateTime()) >= 0 && courseSchedulingDetail.getEndDateTime().compareTo(repairCourse.getEndDateTime()) <= 0)) {
                    repairCourseClashList.add(repairCourse);
                }
            }
        }

//        List<RepairCourse> repairCourseClashList = new ArrayList<>();
//        for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
//            for (RepairCourse repairCourse : repairCourseList) {
//                boolean isConflict = (
//                        (courseSchedulingDetail.getStartDateTime().isBefore(repairCourse.getEndDateTime()) &&
//                                courseSchedulingDetail.getEndDateTime().isAfter(repairCourse.getStartDateTime()))
//                                && !(courseSchedulingDetail.getEndDateTime().isEqual(repairCourse.getStartDateTime()) ||
//                                courseSchedulingDetail.getStartDateTime().isEqual(repairCourse.getEndDateTime()))
//                );
//
//                if (isConflict) {
//                    repairCourseClashList.add(repairCourse);
//                }
//            }
//        }

        return repairCourseClashList;
    }

    /**
     *
     * 临时排班时间冲突
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param gradeId
     * @param localDateTime
     * @return
     */
    @Override
    public List<RepairCourse> getSchedulingClashByLessonType(Integer yearPart, Integer quarterNum, Long studentId, Long gradeId, String localDateTime, Integer lessonType, LocalDateTime startDateTime, LocalDateTime endDateTime) {
        List<RepairCourse> repairCourseList = this.getCourseSchedulingListByLessonType(yearPart, quarterNum, studentId, null, localDateTime, lessonType);

        // 判断是否有一致的时间点
        List<RepairCourse> repairCourseClashList = new ArrayList<>();
        for (RepairCourse repairCourse : repairCourseList) {
            boolean isConflict = (
                    (startDateTime.isBefore(repairCourse.getEndDateTime()) &&
                            endDateTime.isAfter(repairCourse.getStartDateTime()))
                            && !(endDateTime.isEqual(repairCourse.getStartDateTime()) ||
                            startDateTime.isEqual(repairCourse.getEndDateTime()))
            );

            if (isConflict) {
                repairCourseClashList.add(repairCourse);
            }
        }

        return repairCourseClashList;
    }


    /**
     * 获取是否有排课冲突（不包含调、消、缺课）
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param gradeId
     * @param localDateTime
     * @return
     */
    @Override
    public List<CourseSchedulingDetail> getSchedulingClashForDate(Integer yearPart, Integer quarterNum, Long studentId, Long gradeId, String localDateTime){
        List<CourseSchedulingDetail> repairCourseList = this.getSchedulingListForDate(yearPart,quarterNum,studentId,1,localDateTime);
        List<CourseSchedulingDetail> courseSchedulingDetailList = courseSchedulingDetailMapper.getSchedulingForGradeId(yearPart,quarterNum,gradeId,1,localDateTime);

        //冲突排课
        List<CourseSchedulingDetail> repairCourseClashList = new ArrayList<>();
        for (CourseSchedulingDetail courseSchedulingDetail:courseSchedulingDetailList){
            for (CourseSchedulingDetail repairCourse:repairCourseList){
                if ((courseSchedulingDetail.getStartDateTime().compareTo(repairCourse.getStartDateTime())<=0 && courseSchedulingDetail.getEndDateTime().compareTo(repairCourse.getStartDateTime())>=0) || (courseSchedulingDetail.getStartDateTime().compareTo(repairCourse.getEndDateTime())<=0 && courseSchedulingDetail.getEndDateTime().compareTo(repairCourse.getEndDateTime())>=0) || (courseSchedulingDetail.getStartDateTime().compareTo(repairCourse.getEndDateTime())>=0 && courseSchedulingDetail.getEndDateTime().compareTo(repairCourse.getEndDateTime())<=0)){
                    repairCourseClashList.add(repairCourse);
                }
            }
        }
        return repairCourseClashList;
    }

    public List<CourseSchedulingDetail> getSchedulingListForDate(Integer yearPart, Integer quarterNum, Long studentId, Integer lessonType, String localDateTime){
        return courseSchedulingDetailMapper.getSchedulingListForDate(yearPart,quarterNum,studentId,lessonType,localDateTime);
    }


    /**
     * 查找缺课
     */
    @Override
    public Boolean resumeClassesLackCourse(Long gradeId, Long studentId, Integer type, String createdAt, Integer lackType) {
        // 缺课调整
        // 1、停课复课，属于停课缺课（已经添加过新生缺课的也是属于停课缺课）
        // 2、停课复课，如果已经添加过新生缺课，取消了新生缺课，复课时，已经取消的新生缺课课次，不添加缺课

//        Grade grade = gradeMapper.selectById(gradeId);
//        if (grade != null) {
//            Integer lackTypeOne = lackCourseLogMapper.getLackTypeOne(grade.getYearPart(), grade.getQuarterNum(), studentId, grade.getSubjectsId(), grade.getLessonType());
//            if (lackTypeOne != null) {
//                lackType = lackTypeOne;
//            }
//        }

        List<LackCourseLog> lackCourseLogs = courseSchedulingDetailMapper.resumeClassesLackCourse(gradeId, studentId, createdAt);

        for (LackCourseLog lackCourseLog : lackCourseLogs) {
            // 如果有相同的缺课课次，先删除掉再新增
            QueryWrapper<LackCourseLog> wrapper = new QueryWrapper<>();
            wrapper.eq("lesson_type", lackCourseLog.getLessonType());
            wrapper.eq("lesson_num", lackCourseLog.getLessonNum());
            wrapper.eq("subjects_id", lackCourseLog.getSubjectsId());
            wrapper.eq("student_id", lackCourseLog.getStudentId());
            wrapper.eq("year_part", lackCourseLog.getYearPart());
            wrapper.eq("quarter_num", lackCourseLog.getQuarterNum());
            lackCourseLogMapper.delete(wrapper);

            LackCourseLog courseLog = new LackCourseLog();
            courseLog.setSchoolId(lackCourseLog.getSchoolId());
            courseLog.setLessonType(lackCourseLog.getLessonType());
            courseLog.setLessonNum(lackCourseLog.getLessonNum());
            courseLog.setSubjectsId(lackCourseLog.getSubjectsId());
            courseLog.setGradeId(lackCourseLog.getGradeId());
            courseLog.setStudentId(lackCourseLog.getStudentId());
            courseLog.setYearPart(lackCourseLog.getYearPart());
            courseLog.setQuarterNum(lackCourseLog.getQuarterNum());
            courseLog.setYearClassId(lackCourseLog.getYearClassId());
            courseLog.setSchedulingAlwaysId(lackCourseLog.getId());
            Integer gradeS = CommonUtil.getGradeSection(lackCourseLog.getYearClassId());
            courseLog.setGradeSection(gradeS);
            courseLog.setType(type);
            courseLog.setLackType(lackType);
            lackCourseLogMapper.insert(courseLog);
        }
        return true;
    }

    @Override
    public List<CourseSchedulingDetail> getBeforSchedulingOne(Long schedulingDetailId,
                                                              Long schoolId,
                                                              Long studentId,
                                                              Long subjectsId,
                                                              Integer lessonType,
                                                              String schoolDate,
                                                              String startDateTime,
                                                              String endDateTime){
        return courseSchedulingDetailMapper.getBeforSchedulingOne(schedulingDetailId,schoolId,studentId,subjectsId,lessonType,schoolDate,startDateTime,endDateTime);
    }

    /**
     * 添加智能课上午或者下午的所有排课到记上课
     * @return
     */
    @Override
    public RecordCourse addSiginScheduling(Long courseSchedulingDetailId, Long teacherId, Long studentId, String studentName, Integer type, Integer courseType, ReachTypeEnum reachTypeEnum, Long siginInTeacherId, LocalDateTime dateTimeNow, Integer signType, String subjectsId, Integer lessonType){
        LocalDateTime endDateTime = dateTimeNow;

        Long recordCourseId = null;
        try {
            Quarter quarter = iQuarterService.getNowQuarter();
            LocalDate nowDate = LocalDate.now();
            LocalTime currentTime = LocalTime.now();

            // 获取当前日期的中午12点时间
            LocalTime noonTime = LocalTime.NOON;

            String readingStatus = "1";
            List<RepairCourse>  repairCourseList = courseSchedulingDetailMapper.getSchedulingAndRepair(quarter.getYearPart(),quarter.getNum(),teacherId,studentId.toString(),nowDate.toString(),subjectsId,lessonType,readingStatus);
            // 如果需要获取包含日期的中午12点时间
            LocalDateTime noonDateTime = LocalDateTime.of(LocalDateTime.now().toLocalDate(), noonTime);

            List<RepairCourse> reasonList = new ArrayList<>();
            for (RepairCourse repairCourse : repairCourseList) {
                //不算精品课
                if (!repairCourse.getLessonType().equals(1)){
                    if (!repairCourse.getId().equals(courseSchedulingDetailId)) {
                        if (currentTime.isBefore(LocalTime.NOON)) {
                            //上午
                            if (repairCourse.getStartDateTime().isBefore(noonDateTime)){
                                reasonList.add(repairCourse);
                            }
                        } else {
                            //下午
                            if (repairCourse.getStartDateTime().isAfter(noonDateTime)){
                                reasonList.add(repairCourse);
                            }
                        }
                    }
                }
            }

            if (reasonList.size()>1){
                for (RepairCourse repairCourse : reasonList) {
                    if (repairCourse.getEndDateTime().isAfter(endDateTime)){
                        endDateTime = repairCourse.getEndDateTime();
                    }
                }
            }
            //添加到记上课记录
            for (RepairCourse repairCourse : reasonList) {
                recordCourseId = iRecordCourseService.addForSchedulingId(repairCourse.getSchedulingDetailId(),studentId,studentName,type,courseType,reachTypeEnum,siginInTeacherId,dateTimeNow,signType,null);
            }
        }catch (Exception e){

        }
        RecordCourse recordCourse = new RecordCourse();
        recordCourse.setId(recordCourseId);
        recordCourse.setEndDateTime(endDateTime);
        return recordCourse;
    }

}
